package com.study.system.adservice.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 广告更新定时任务的配置
 */
@EnableScheduling //启动定时任务
@Configuration
public class UpdateAdTaskConfig {

    private Logger logger = LoggerFactory.getLogger(UpdateAdTaskConfig.class);

    /**
     * 定时任务
     */
    @Scheduled(cron = "*/5 * * * * ?")
    public void updateAd() throws IOException {
        //创建网络URL 调用lua脚本
        URL url = new URL("http://localhost:8888/ad_update?sid=1");
        //创建网络连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置连接方法
        conn.setRequestMethod("GET");
        //设置内容类型
        conn.addRequestProperty("Content-Type","application/json;charset=utf-8");
        //获得网络输入流
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder stringBuilder = new StringBuilder();
        //逐行读取文字
        String line = null;
        while((line = reader.readLine()) != null){
            stringBuilder.append(line);
        }
        reader.close();
        logger.info("同步广告完成:{}",stringBuilder);
    }
}
